package com.eyeem.recyclerviewtools.sample;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.support.v7.widget.Toolbar;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.eyeem.recyclerviewtools.LoadMoreOnScrollListener;
import com.eyeem.recyclerviewtools.StaggeredLayoutManagerUtils;
import com.eyeem.recyclerviewtools.adapter.WrapAdapter;
import com.eyeem.recyclerviewtools.sample.adapter.DataAdapter;
import com.eyeem.recyclerviewtools.sample.data.Data;
import com.eyeem.recyclerviewtools.sample.utils.BlurUtil;
import com.eyeem.recyclerviewtools.sample.widget.Header;

import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by budius on 26.05.16.
 */
public class MaterialDesiginActivity extends BaseActivity implements LoadMoreOnScrollListener.Listener {
    private LinearLayout head_layout;
    private SwipeRefreshLayout swipeRefreshLayout;
    //private TabLayout toolbar_tab;
    private RecyclerView recycler;
    private CollapsingToolbarLayout mCollapsingToolbarLayout;
    private DataAdapter adapter;
    private WrapAdapter wrapAdapter;
    SampleActivity.CollapsingToolbarLayoutState state = SampleActivity.CollapsingToolbarLayoutState.EXPANDED;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_material_design);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);

        AppBarLayout app_bar_layout = (AppBarLayout) findViewById(R.id.app_bar_layout);
        Toolbar mToolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(mToolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        head_layout = (LinearLayout) findViewById(R.id.head_layout);
        //
        swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_container);
        mCollapsingToolbarLayout = (CollapsingToolbarLayout) findViewById(R.id.collapsing_toolbar_layout);

        boolean useRxJava = true;
        if (useRxJava) {
            blur();
        } else {
            Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.bg);
            head_layout.setBackgroundDrawable(new BitmapDrawable(BlurUtil.fastblur(this, bitmap, 180)));
            mCollapsingToolbarLayout.setContentScrim(new BitmapDrawable(BlurUtil.fastblur(this, bitmap, 180)));
        }


        //使用CollapsingToolbarLayout必须把title设置到CollapsingToolbarLayout上，设置到Toolbar上则不会显示
        app_bar_layout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
            @Override
            public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
                swipeRefreshLayout.setEnabled(verticalOffset >= 0);
                if (verticalOffset <= -head_layout.getHeight() / 2) {
                    mCollapsingToolbarLayout.setTitle("涩郎");
                } else {
                    mCollapsingToolbarLayout.setTitle(" ");
                }
            }
        });
        Toolbar.OnMenuItemClickListener onMenuItemClick = new Toolbar.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem menuItem) {
                String msg = "";
                switch (menuItem.getItemId()) {
                    case R.id.action_settings:
                        msg += "设置";
                        break;
                }

                if (!msg.equals("")) {
                    Toast.makeText(MaterialDesiginActivity.this, msg, Toast.LENGTH_SHORT).show();
                }
                return true;
            }
        };

        mToolbar.setOnMenuItemClickListener(onMenuItemClick);
        //toolbar_tab = (TabLayout) findViewById(toolbar_tab);
        recycler = (RecyclerView) findViewById(R.id.recycler);

        mCollapsingToolbarLayout.setExpandedTitleGravity(Gravity.CENTER);
        mCollapsingToolbarLayout.setCollapsedTitleGravity(Gravity.CENTER);


        // Adapter
        adapter = DataAdapter.generateRandom(this);
        wrapAdapter = new WrapAdapter(adapter);
        // Layout manager
        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this);
        recycler.setLayoutManager(layoutManager);
        recycler.setAdapter(wrapAdapter);
        // Header
        wrapAdapter.addHeader(new Header(this));
        // Load more scroller
        recycler.addOnScrollListener(new LoadMoreOnScrollListener(this));
        //
        dismissRefresh(swipeRefreshLayout);

    }

    private void blur() {
        Observable.create(
                new Observable.OnSubscribe<BitmapDrawable>() {
                    @Override
                    public void call(Subscriber<? super BitmapDrawable> subscriber) {
                        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.bg);
                        BitmapDrawable bitmapDrawable = new BitmapDrawable(BlurUtil.fastblur(MaterialDesiginActivity.this, bitmap, 180));
                        subscriber.onNext(bitmapDrawable);
                        subscriber.onCompleted();
                    }
                })
                .subscribeOn(Schedulers.newThread())// 在非UI线程中执行
                .observeOn(AndroidSchedulers.mainThread())// 在UI线程中执行结果
                .subscribe(new Subscriber<BitmapDrawable>() {
                    @Override
                    public void onNext(BitmapDrawable bitmapDrawable) {
                        head_layout.setBackgroundDrawable(bitmapDrawable);
                        mCollapsingToolbarLayout.setContentScrim(bitmapDrawable);
                    }

                    @Override
                    public void onCompleted() {
                    }

                    @Override
                    public void onError(Throwable e) {
                    }
                });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_space, menu);
        return true;
    }


    @Override
    public void onLoadMore(RecyclerView recyclerView) {
        //toast("Load more");
        wrapAdapter.showLoadMore();
        recyclerView.postDelayed(new Runnable() {
            @Override
            public void run() {

                for (int i = 0; i < 5; i++) {
                    adapter.data.add(Data.newRandom(MaterialDesiginActivity.this));
                }

                if (recycler.getLayoutManager() instanceof StaggeredGridLayoutManager) {
                    StaggeredLayoutManagerUtils.onItemChanged(recycler, 0);
                }
                adapter.notifyDataSetChanged();
                wrapAdapter.hideLoadMore();

            }
        }, 1000);
    }
}
